//
//  ViewController.m
//  省会和城市
//
//  Created by student on 16/2/28.
//  Copyright © 2016年 niit. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UIPickerView *pickView;
@property(nonatomic,strong)NSArray *statePlist;
@property(nonatomic,strong)NSArray *cityPlist;
@property(nonatomic,strong)NSMutableArray *stateArray;
@property(nonatomic,strong)NSMutableArray *cityArray;
@property(nonatomic,strong)NSMutableDictionary *cityDict;
@property(nonatomic,strong)NSMutableDictionary *stateDict;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle]pathForResource:@"area1" ofType:@"plist"];
    self.statePlist = [NSArray arrayWithContentsOfFile:path];
    self.stateArray = [NSMutableArray array];
    self.cityArray = [NSMutableArray array];
    for(int i=0;i<self.statePlist.count;i++)
    {
        self.stateDict = self.statePlist[i];
        [self.stateArray addObject:self.stateDict[@"State"]];  //第一列数组
        
    }
    self.stateDict = self.statePlist[0];
    self.cityPlist = self.stateDict[@"Cities"];
    for(int i=0;i<self.cityPlist.count;i++)
    {
        self.cityDict = self.cityArray[i];
        [self.cityArray addObject:self.cityDict[@"city"]];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
    
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(component == 0)
    {
        return self.stateArray.count;
    }
    else
    {
        return self.cityArray.count;
    }
}
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(component == 0)
    {
        return self.stateArray[row];
        
    }
    else
    {
        return self.cityArray[row];
    }
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return 120;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 40;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(component == 0)
    {
        self.stateDict = self.statePlist[row];
        self.cityPlist = self.stateDict[@"Cities"];
        [self.cityArray removeAllObjects];
        for(int i = 0;i<self.cityPlist.count;i++)
        {
            self.cityDict = self.cityPlist[i];
            [self.cityArray addObject:self.cityDict[@"city"]];
        }
        [self.pickView reloadComponent:1];
        [self.pickView selectRow:0 inComponent:1 animated:YES];
    }
}

@end
